import { loginHandle, getAuthList } from '@/api/login'
import { getToken, setToken, removeToken, setCookie, getCookie, removeCookie } from '@/utils/auth'

const record = {
	state: {
		user: '',
		token: getToken(),
		name: getCookie('Admin-Name'),
		avatar: '',
		introduction: '',
		roles: ''
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_INTRODUCTION: (state, introduction) => {
			state.introduction = introduction
		},
		SET_NAME: (state, name) => {
			state.name = name
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
		},
		SET_ROLES: (state, roles) => {
			state.roles = roles
		}
	},

	actions: {
		// 用户名登录
		LoginByUsername({ commit }, userInfo) {
			const username = userInfo.username.trim()
			return new Promise((resolve, reject) => {
				loginHandle(username, userInfo.password).then(response => {
					const param = response.data
					commit('SET_TOKEN', param.token)
					commit('SET_NAME', param.username)
					setToken(param.token)
					setCookie('Admin-Name', param.username)
					// commit('SET_TOKEN', 'admin')
					// setToken('admin')
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 获取用户信息
		GetUserInfo({ commit, state }) {
			return new Promise((resolve, reject) => {
				getAuthList().then(response => {
					if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
						// reject('error')
					}
					commit('SET_ROLES', 'normal')
					// const data = response.data
					// commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
					// commit('SET_INTRODUCTION', data.introduction)
					resolve(response)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 登出
		LogOut({ commit, state }) {
			return new Promise((resolve, reject) => {
				commit('SET_TOKEN', '')
				commit('SET_ROLES', '')
				removeToken()
				removeCookie('Admin-Name')
				resolve()
			})
		},
		// 前端 登出
		FedLogOut({ commit }) {
			return new Promise(resolve => {
				commit('SET_TOKEN', '')
				removeToken()
				resolve()
			})
		},
		setRoles({ commit }, roles) {
			return new Promise((resolve, reject) => {
				commit('SET_ROLES', roles)
				resolve()
			})
		}
	}
}

export default record
